import { fork } from 'child_process';
import { app } from 'electron';
import path from 'path';
import _ from 'lodash';
import Configuration from './config';

class ScanThreadController {
    constructor() {
        // this.cachePath = path.join(app.getPath('userData'), 'cache.json');
        this.thread = null;
        this.selectCache = [];
        this.imageSelectSender = null;
        this.lastScanPath = null;

        this.restartThread();
    }
    get Sender() {
        return this.imageSelectSender;
    }
    set Sender(value) {
        this.imageSelectSender = value;
    }
    restartThread() {
        if (!_.isNull(this.thread)) this.exitThread();
        let params = [];
        if (Configuration.config.shuffle) params.push('-s');
        this.thread = fork(path.join(__dirname, 'scan.js'), params);

        this.thread.on('message', data => {
            switch (data.type) {
                case 'selected':
                    if (_.isNull(controller.Sender)) return;
                    controller.Sender.send('image-selected', data.content);
                    break;
            }
        });
        this.thread.on('error', () => {
            this.restartThread();
        });
        if (!_.isNull(this.lastScanPath)) {
            this.scanPath(this.lastScanPath);
        }
    }
    setShuffle(value) {
        try {
            this.thread.send({ type: 'shuffle', sign: value });
        } catch (err) {
            console.error(err.message);
        }
    }
    scanPath(selectedPath) {
        if (_.isUndefined(selectedPath) || _.isNull(selectedPath)) return;
        try {
            this.lastScanPath = selectedPath;
            this.thread.send({ type: 'scan', target: selectedPath });
        } catch (err) {
            console.error(err.message);
        }
    }
    selectOnePicture() {
        try {
            this.thread.send({ type: 'select' });
        } catch (err) {
            console.error(err.message);
        }
    }
    exitThread() {
        try {
            this.thread.send({ type: 'exit' });
            // this.thread.kill(0);
        } catch (err) {
            console.error(err.message);
        }
    }
}

const controller = new ScanThreadController();

export default controller;
